import type { BasicLayoutProps, Settings as LayoutSettings } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
import { notification } from 'antd';
import type { RequestConfig, RunTimeLayoutConfig } from 'umi';
import { history, Link } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
//import { currentUser as queryCurrentUser } from './services/ant-design-pro/api';
// import { ApiFilled, BookOutlined, LinkOutlined } from '@ant-design/icons';
import {userCurrentUser as queryCurrentUser} from './services/user-login/userLogin'
import {userMenuList,userMenuListPath} from './services/user-menu/userMenu'
import type {MenuDataItem} from '@ant-design/pro-layout'
// import { currentUser } from './services/ant-design-pro/api';
const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  menuData:MenuDataItem[];
  currentUser?: API.CurrentUser;
  fetchUserInfo?: (params:any) => Promise<API.CurrentUser | undefined>;
}> {

  // user onclick login
  const fetchUserInfo = async (params:any) => {
    try {
      const msg = await queryCurrentUser({userName:params.username,passWord:params.password});
      if(msg.data){
        console.log("msg.data----------------------------app.tsx-----------------------------------------------")
        console.log(msg)
        await localStorage.setItem("userinfo",JSON.stringify(msg.data));
        await localStorage.setItem("token",msg.token)
        params = {
          menuLists:msg.data.menuList
        }
        const menuData = await userMenuList(params);
        console.log(menuData)
        localStorage.setItem("menuDataList",JSON.stringify(menuData))

        const menuDataPath = await userMenuListPath(params)
        localStorage.setItem("menuDataListPath",JSON.stringify(menuDataPath))
      }
      return msg.data;
    } 
    catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };


  //page show
  // 如果是登录页面，不执行
  if (history.location.pathname !== loginPath) {

    //get 
    let menuData = JSON.parse(localStorage.getItem("menuDataList"))
    let currentUser = JSON.parse(localStorage.getItem("userinfo")) || {}
    
    //const userList = await fetchUserInfo();
    console.log("userList-------------------------------")
    //console.log(userList)

    return {
      fetchUserInfo,
      currentUser,
      menuData,
      settings: {},
    };
  }

  console.log("app.tsx--执行------------------------------------------")

  return {
    fetchUserInfo,
    menuData:[],
    settings: {},
  };
}


// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout = ({ initialState }:{
  initialState:{settings?: LayoutSettings; menuData:MenuDataItem[];currentUser?:API.CurrentUser}
}):BasicLayoutProps => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    footerRender: () => <Footer />,
    onPageChange: () => {

      let menuData = JSON.parse(localStorage.getItem("menuDataList"))
      let menuDataPath = JSON.parse(localStorage.getItem("menuDataListPath"))
      initialState.menuData = menuData
      const { location } = history;

      // 判断token-------------------------
      const token = localStorage.getItem("token");
      if(token?.length < 2){
        history.push(loginPath)
      }
      //debugger
      console.log(history.location.pathname)
      // scurity user message
      if(initialState.menuData !== null){
        
        console.log("打印userlogin进来了.................")

        if(history.location.pathname === loginPath){
          history.push(loginPath)
          return;
        }
        
        console.log("数组不为空进来了---------------------")
        let arrStr = menuDataPath.filter((item:string) => item === location.pathname)
        //let arrStrPro = menuData.filter((item: { path: string; }) => item.path=== '/user/login/str')
        
        console.log(arrStr)
        if(arrStr.length <= 0){

          history.push('/404')
      
        }

      }else{
        history.push(loginPath);
      }
      
      console.log("app.tsx-------------------------------------------------------------onPageChange---")
      // console.log(menuData)
      
      console.log(initialState)
      //console.log(menuData)
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
        return;
      }

    },
    menuHeaderRender: undefined,
    menuDataRender:(menuData)=> initialState.menuData || menuData,
    ...initialState?.settings,
  };
};